package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 */
public class Utils {
    public static WebDriver driver = null;
    public WebDriverWait wait = null;
    /**
     * 获取驱动对象
     */
    public static WebDriver createDriver(){
        if (driver == null){
            //下载驱动
            WebDriverManager.chromedriver().setup();
            //添加配置：允许访问所有的链接
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--remote-allow-origins=*");
            //启动浏览器时自动最大化窗口
            options.addArguments("--start-maximized");
            //创建驱动对象
            driver = new ChromeDriver(options);
            //隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
        }
        return driver;
    }
    /**
     * 构造方法
     */
    public Utils(String url){
        //调用driver对象
        driver = createDriver();
        //浏览器打开指定的url对应的页面
        driver.get(url);
        wait = new WebDriverWait(driver,Duration.ofSeconds(3));
    }

    /**
     * 屏幕截图
     */
    public void  ScreenShot(String str) throws IOException {
        //定义年月日格式
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        //定义时分秒毫秒格式
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("HHmmssSS");
        //将当前时间转换为对应格式的字符串
        String dirTime = simpleDateFormat1.format(System.currentTimeMillis());
        String fileTime = simpleDateFormat2.format(System.currentTimeMillis());
        //定义图片文件名
        String filename = "./src/test/java/images/" + dirTime  + "/" + str + "-" + fileTime +".png";
        //执行截图并保存
        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcFile,new File(filename));
    }
    /**
     * 销毁driver对象-关闭浏览器
     */
    public static void quit(){
        if (driver != null){
            //彻底终止整个浏览器会话
            driver.quit();
        }
    }
}
